﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ZLCMS.Data.Model;
using NHibernate;
using ZLCMS.Business;
using NHibernate.Criterion;
using ZLCMS.Business.Commands.SessionCommands;
using DotNet.Common.Command;
using DotNet.Common.NHibernateUtil;
using ZLCMS.Web.Wap.Code;

namespace ZLCMS.Web.MemberUser
{
    public partial class MyAddress : WebMemberPageBase
    {
        protected MemberInfo _memberDb;
        public MemberAddress _memberAddress;

        protected int _addrId;

        protected void Page_Load(object sender, EventArgs e)
        {
            _memberDb = Master.LoadMember();
            MemberCategory1.MenuIndex = "shdz";
            if (!IsPostBack)
            {
                try
                {
                    _addrId = int.Parse(Request["id"]);
                }
                catch (System.Exception ex)
                {
                    _addrId = -1;
                }

                if (Request["opt"] == "del")
                {
                    DelelteAddress();
                }
                else if (Request["opt"] == "setdefault")
                {
                    SetDefault();
                }

                BindAddress();
                InitAddress();
            }
            else
            {
                _addrId = (int)ViewState["id"];
            }
        }

        //设默认地址
        private void SetDefault()
        {
            ClientScriptManager csm = this.Page.ClientScript;

            try
            {
                HandleAddressCommandParameter cmdParam = new HandleAddressCommandParameter();

                cmdParam.OptCode = "S";
                cmdParam.UserCode = _memberDb.AccountId;
                cmdParam.TargetId = _addrId;

                CommandResult cmdResult = new HandleAddressCommand().Execute(cmdParam) as CommandResult;

                if (cmdResult.Error)
                {
                    throw new Exception(cmdResult.ErrorMsg);
                }

                Response.Redirect("/MemberUser/MyAddress.aspx?id=0&msg=操作成功");
            }
            catch (System.Exception ex)
            {
                csm.RegisterStartupScript(this.GetType(), "error_tip", "alert('" + ex.Message + "');", true);
                return;
            }
        }

        protected void DelelteAddress()
        {
            ClientScriptManager csm = this.Page.ClientScript;

            try
            {
                HandleAddressCommandParameter cmdParam = new HandleAddressCommandParameter();

                cmdParam.OptCode = "D";
                cmdParam.UserCode = _memberDb.AccountId;
                cmdParam.TargetId = _addrId;

                CommandResult cmdResult = new HandleAddressCommand().Execute(cmdParam) as CommandResult;

                if (cmdResult.Error)
                {
                    throw new Exception(cmdResult.ErrorMsg);
                }

                Response.Redirect("/MemberUser/MyAddress.aspx?id=0&msg=操作成功");
            }
            catch (System.Exception ex)
            {
                csm.RegisterStartupScript(this.GetType(), "error_tip", "alert('" + ex.Message + "');", true);
                return;
            }
        }

        protected void BindAddress()
        {
            using (ISession session = SessionFactoryHelper.CreateSession())
            {
               

                IList<MemberAddress> list = session.CreateQuery("from MemberAddress where MemberAccount=:acc").
                    SetParameter("acc", _memberDb.AccountId).
                    List<MemberAddress>();

                //IList<MemberAddress> listsource = new List<MemberAddress>();
                //foreach (MemberAddress addr in list)
                //{
                //    addressCount++;
                //    listsource.Add(new MemberAddress() { Receiver = addr.Receiver + "，" + addr.Address + "，" + addr.Mobile, Id = addr.Id });
                //}
                rpt_address.DataSource = list;
                rpt_address.DataBind();
            }
        }

        protected void InitAddress()
        {
            //新建
            if (_addrId == 0)
            {
                ViewState["id"] = 0;//0表示新建
                return;
            }

            try
            {
                using (ISession session = SessionFactoryHelper.CreateSession())
                {
                    IList<DataProvince> provinceList = session.CreateCriteria<DataProvince>().List<DataProvince>();

                    //rptProvince.DataSource = provinceList.ToList();

                    //rptProvince.DataBind();
                    sel_province.DataSource = provinceList.ToList();
                  
                    sel_province.DataValueField = "Code";
                    sel_province.DataTextField = "Name";
  sel_province.DataBind();
                    //查询该用户是否有这个地址的信息
                    _memberAddress = session.CreateCriteria<MemberAddress>().Add(Expression.Eq("Id", _addrId)).Add(Expression.Eq("MemberAccount", _memberDb.AccountId)).UniqueResult<MemberAddress>();

                    if (_memberAddress == null)
                    {
                        ViewState["id"] = -1;//-1表示无数据
                        _addrId = -1;
                    }

                    tb_name.Text = _memberAddress.Receiver;
                    tb_address.Text = _memberAddress.Address;
                    tb_phone.Text = _memberAddress.Phone;
                    if(_memberAddress.Status=="1")
                    {
                        ckb_default_address.Checked = true;
                    }


                    ViewState["id"] = _memberAddress.Id;
                    _addrId = _memberAddress.Id;

                    if (_memberAddress == null)
                    {
                        ViewState["id"] = -1;//-1表示无数据
                        _addrId = -1;
                    }

                    ViewState["id"] = _memberAddress.Id;
                    _addrId = _memberAddress.Id;
                }
            }
            catch (System.Exception ex)
            {

            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            ClientScriptManager csm = this.Page.ClientScript;

            if (tb_name.Text == ""|| sel_province.Value == "-1" || Request[sel_city.Name] == "-1" || Request[sel_area.Name] == "-1" || tb_address.Text == "" || tb_phone.Text == "")
          {
              csm.RegisterStartupScript(this.GetType(), "error_tip", "alert('请完善地址信息!'); ", true);
              return;
          }

            try
            {
                HandleAddressCommandParameter cmdParam = new HandleAddressCommandParameter();

                if (_addrId > 0)
                {
                    cmdParam.OptCode = "M";
                    cmdParam.TargetId = _addrId;
                }
                else
                {
                    cmdParam.OptCode = "A";
                }

                cmdParam.UserCode = _memberDb.AccountId;
                cmdParam.Receiver = tb_name.Text;
                cmdParam.Province =  sel_province.Value;
                cmdParam.City = Request[sel_city.Name];
                cmdParam.Area = Request[sel_area.Name];
                cmdParam.Address =tb_address.Text;
                cmdParam.Phone = tb_phone.Text;
                cmdParam.Status = ckb_default_address.Checked ? "1" : ""; ;

                CommandResult cmdResult = new HandleAddressCommand().Execute(cmdParam) as CommandResult;

                if (cmdResult.Error)
                {
                    throw new Exception(cmdResult.ErrorMsg);
                }

                Response.Redirect("/MemberUser/MyAddress.aspx?id=0&msg=操作成功");
            }
            catch (System.Exception ex)
            {
                csm.RegisterStartupScript(this.GetType(), "error_tip", "alert('" + ex.Message + "');", true);
                return;
            }
        }
    }
}
